//
//  LocationManager.swift
//  LocationManager
//
//  Created by Ben on 2021/8/17.
//

import SwiftUI
import CoreLocation

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
    
    static let shared = LocationManager()
    
    private var manager: CLLocationManager = CLLocationManager()
    
    @Published var cityName: String?
    @Published var provinceName: String?
    
    override init() {
        super.init()
        
        manager.delegate = self
        manager.requestWhenInUseAuthorization()
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        Dlog(error)
    }
    
    // 该方法为定位成功的代理方法
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        
        manager.stopUpdatingLocation()
        
        guard let location = locations.last?.coordinate else {
            return
        }
        
        // 通过地理反编码得到位置的详细信息
        let geoc = CLGeocoder()
        
        geoc.reverseGeocodeLocation(CLLocation(latitude: location.latitude, longitude: location.longitude)) { placemarks, error in
            
            guard let placemark = placemarks?.first else {
                return
            }
            
            // locality就表示当前定位的城市名称

            guard let province_name = placemark.administrativeArea else {
                return
            }
            guard let city_name = placemark.locality else {
                return
            }

            DispatchQueue.main.async {
                self.provinceName = province_name
                self.cityName = city_name
            }
            
        }
    }
    
    func startUpdating() {
        cityName = nil
        manager.startUpdatingLocation()
    }
}
